

from okx import PublicData, Trade, MarketData, Account

from config import oksConfig

api_key = oksConfig.getAPIKey()
api_secret_key = oksConfig.getSecretKey()
passphrase = oksConfig.getPassPhrase()
flag = oksConfig.getFlag()
print("api_key ", api_key)
print("api_secret_key ", api_secret_key)
print("passphrase ", passphrase)
print("flag ", flag)

### 交易訂單
# 买
# {
# instId: "ETH-USDT",
#  ordType: "market",
#  side: "buy",
#  sz: "1",
#  tdMode: "cash"
#  ,tgtCcy : "quote_ccy"
#  _feReq: true
#  }
def buy(instId, sz):
    print("买入 " + str(instId).upper() + " : " + str(sz))
    TradeAPI = Trade.TradeAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag=flag)
    response = TradeAPI.place_order(instId=str(instId).upper(),
                         ordType="market",
                         side="buy",
                         sz=sz,
                         tdMode="cash",
                         tgtCcy="quote_ccy")
    if response['code'] != '0':
        # 失败
        print("buy " + str(instId).upper() + " : " + str(sz) + "failed, reason: " + response['msg'] + response['data'][0]['sMsg'])
        return
    return response['data'][0]['ordId']

# 卖
# {instId: "ETH-USDT",
# ordType: "market",
#   side: "sell",
#    sz: "0.0001"
# tdMode: "cash",
# tgtCcy: "base_ccy",
# _feReq: true}
def sell(instId, sz):
    print("卖出 " + str(instId) + " : " + str(sz))
    TradeAPI = Trade.TradeAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag=flag)
    response = TradeAPI.place_order(instId=str(instId).upper(),
                         ordType="market",
                         side="sell",
                         sz=sz,
                         tdMode="cash",
                         tgtCcy="base_ccy")
    if response['code'] != '0':
        # 失败
        print("sell " + str(instId).upper() + " : " + str(sz) + "failed, reason: " + response['msg'])
        return
    return response['data'][0]['ordId']

def getOrder(instId, orderId, side):
    TradeAPI = Trade.TradeAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag=flag)
    response = TradeAPI.get_order(instId=str(instId).upper(), ordId=orderId)
    if response['code'] != '0':
        # 失败
        print("getOrder failed, orderID: " + orderId)
        return
    if side == "buy":
        return float(response['data'][0]['fillSz']) + float(response['data'][0]['fee'])
    if side == "sell":
        return float(response['data'][0]['fillSz']) * float( response['data'][0]['fillPx']) +  float(response['data'][0]['fee'])

def getSellPrice(instId, orderId):
    return getOrder(instId, orderId, "sell")

def getBuyCount(instId, orderId):
    return getOrder(instId, orderId, "buy")


######################## 市場信息
# "instType": "SPOT", "instId":"ETH-USDT"
def getMarkPrice(instType, instId):
    PublicDataApi = PublicData.PublicAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag=flag)
    response = PublicDataApi.get_mark_price(instType=str(instType).upper(), instId=str(instId).upper())
    if response['code'] != '0':
        # 失败
        print("getMarkPrice failed, instId: " + instId)
        return
    return response['data'][0]['markPx']

# ['1711677600000', 开始时间，Unix时间戳的毫秒数格式，如 1597026383085
# '3569.88', 开盘价格
# '3571.94', 最高价格
# '3554.34', 最低价格
# '3561.39', 收盘价格
# '13788.811292', 交易量，以张为单位
# 如果是衍生品合约，数值为合约的张数。
# 如果是币币/币币杠杆，数值为交易货币的数量。
# '49120163.48347908', 交易量，以币为单位
# 如果是衍生品合约，数值为交易货币的数量。
# 如果是币币/币币杠杆，数值为计价货币的数量。
# '49120163.48347908', 交易量，以计价货币为单位
# 如 BTC-USDT和BTC-USDT-SWAP，单位均是USDT。
# BTC-USD-SWAP单位是USD。
# '1'K线状态
# 0：K线未完结
# 1：K线已完结
# ]
def getKData(instId, after, before, bar, limit):
    MarketDataApi = MarketData.MarketAPI(api_key, api_secret_key, passphrase, use_server_time=False, flag=flag)
    response= MarketDataApi.get_candlesticks(instId=instId, after=after, before=before, bar=bar, limit=limit)
    if response['code'] != '0':
        # 失败
        print("getKData failed, instId: " + instId)
        return
    return response['data']

def getAccountBalance(instId):
    accountAPI = Account.AccountAPI(api_key, api_secret_key, passphrase, False, flag)

    # 查看账户账单详情 （近三个月内）
    response = accountAPI.get_account_balance(instId)
    if response['code'] != '0':
        # 失败
        print("getAccountBalance, instId: " + instId)
        return
    return response['data'][0]['details'][0]['cashBal']

if __name__ == '__main__':
#     # orderId = buy("ETH-USDT", 1000)
#     # num = getBuyCount("ETH-USDT", orderId)
#     # print(num)
#     # orderId2 = sell("ETH-USDT", 0.1)
#     # num2 = getSellCount("ETH-USDT", orderId2)
#     # print(num2)
#     print(getMarkPrice("MARGIN", "ETH-USDT"))
#     data = getKData("ETH-USDT", 1711768274813 ,1711472234000, "15m", 329)
    # for item in data:
    print(getAccountBalance("WLD"))

